package com.hzit.config;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

	public AgeRoutePredicateFactory() {
		super(Config.class);
	}

	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return exchange -> {
			String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
			if(StrUtil.isNotBlank(ageStr)){
				int age = new Integer(ageStr);
				// 指定参数的范围
				return age >= config.getMinAge() && age <= config.getMaxAge();
			}
			return false;
		};
	}
	// 指定两个参数的顺序
	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge","maxAge");
	}
	// 指定传递的参数
	@Data
	@NoArgsConstructor
	public static class Config {
		private Integer minAge;
		private Integer maxAge;
	}
}
